package pl.polsl.mmm.projectcomm.util.bluetooth;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;

import java.io.IOException;
import java.util.UUID;

import pl.polsl.mmm.projectcomm.GameActivity;

/**
 * Klasa reprezentuje obiekt oczekujący na połączenie klienta
 *
 * Created by michal on 28.12.14.
 */
public class AcceptThread extends Thread {
    private final BluetoothServerSocket mmServerSocket;
    BluetoothAdapter mBluetoothAdapter;
    String uuidString = "a3137d00-8eac-11e4-b4a9-0800200c9a66";
    Handler handler;
    Activity activity;
    private static ConnectedThread connectedThread = null;

    public AcceptThread(Activity pActivity, BluetoothAdapter bluetoothAdapter, Handler pHandler) {
        // Use a temporary object that is later assigned to mmServerSocket,
        // because mmServerSocket is final
        mBluetoothAdapter = bluetoothAdapter;
        BluetoothServerSocket tmp = null;
        handler = pHandler;
        activity = pActivity;
        try {
            // MY_UUID is the app's UUID string, also used by the client code
            tmp = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("comm", UUID.fromString(uuidString));
        } catch (IOException e) {
        }
        mmServerSocket = tmp;
    }

    public void run() {
        BluetoothSocket socket = null;
        // Keep listening until exception occurs or a socket is returned
        while (true) {
            try {
                socket = mmServerSocket.accept();
            } catch (IOException e) {
                break;
            }

            if (socket != null) {

                connectedThread = new ConnectedThread(socket, handler);

                // nasłuchiwanie
                connectedThread.start();

                // Po nawiązaniu połączenia przejście do ekranu gry
                Intent intent = new Intent(activity, GameActivity.class);
                activity.startActivity(intent);
            }
        }
    }

    // Wysłanie danych przez bluetooth
    public static void write(byte array[]) {
        if (connectedThread != null) {
            connectedThread.write(array);
        }
    }

    /**
     * Will cancel the listening socket, and cause the thread to finish
     */
    public void cancel() {

        try {
            connectedThread = null;
            mmServerSocket.close();
        } catch (IOException e) {
        }
    }
}